import Vue from 'vue'
import VueRouter from 'vue-router'
import Login from '../components/Login.vue'
import Home from '../components/Home.vue'

Vue.use(VueRouter)

const routes = [
  {
    path:'/',
    redirect: 'login'
  },
  {
    path: '/login', 
    component: Login
  },
  {
    path: '/home',
    component: Home
  }
]

const router = new VueRouter({
  routes
})

//路由导航
router.beforeEach((to, from, next) => {
  //to:将要访问的路径
  //from:从何路径跳转而来
  //next():函数,表示放行.参数为空表示直接跳转
  if(to.path === '/login') {
    next()
  }
  else {
    const tokenStr = window.sessionStorage.getItem('token')
    if(!tokenStr) {  //注意:这里仅判断当前浏览器是否有token,如果出于安全考虑,则需要通过后端与当前浏览器中做比对
      next('/login')
    }
    else {
      next()
    }
  }
})

export default router
